package com.file.system.tools;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.file.system.entity.res.DataBusinessPage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;


/**
 * @Description （数据格式化）
 * @Author bao
 * @Date 2017/3/29 21:16
 */
public class Formater {
    private static Pattern humpPattern = Pattern.compile("[A-Z]");



    /**
     * 字符串转LocalDateTime
     */
    public static LocalDateTime convertToLocalDateTime(String dateTimeString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
        return dateTime;
    }

    /**
     * 非空且符合 “yyyy-MM-dd HH:mm:ss” 的格式要求
     */
    public static boolean isDateTimeValid(String dateTimeString) {
        if (dateTimeString != null && !dateTimeString.isEmpty()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                format.parse(dateTimeString);
                return true;
            } catch (ParseException e) {
                return false;
            }
        }
        return false;
    }


    /**
     * 判断两个日期是否是同一天
     */
    public static boolean isSameDate(Date date1, LocalDateTime date2) {
        LocalDate localDate = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return localDate.isEqual(date2.toLocalDate());
    }

    /**
     * 根据日期获取月份
     */
    public static int getMonthFromDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1; // Calendar.MONTH 的范围是 0-11，所以需要加 1
    }

    /**
     * 根据日期获取年份
     */
    public static int getYearFromDate(Date date) {
        // 创建一个Calendar实例，并将日期设置为当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 使用Calendar类获取当前年份
        int year = calendar.get(Calendar.YEAR);
        return year;
    }


    /**
     * 根据日期获取年月yyyyMM
     */
    public static int getYMFromDate(Date date) {
        return getYearFromDate(date) * 100 + getMonthFromDate(date);
    }

    /**
     * 根据日期获取年月yyyyMM
     */
    public static int getYMFromDate(LocalDateTime date) {
        int year = date.getYear();
        int month = date.getMonthValue();
        return year * 100 + month;
    }


    // 辅助方法，将LocalDateTime转换为Date
    public static Date convertToDate(LocalDateTime dateTime) {
        return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
    }


    // 将Date类型转换为LocalDateTime
    public static LocalDateTime convertToLocalDateTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }


    /**
     * 判断是否为基本类型
     */
    public static boolean isBasicClass(Class<?> clazz) {
        if (String.class.equals(clazz)) {
            return true;
        }
        //赋值字段  整数类型
        if (Long.class.equals(clazz) || long.class.equals(clazz)) {
            return true;
        }
        if (Byte.class.equals(clazz) || byte.class.equals(clazz)) {
            return true;
        }
        if (Short.class.equals(clazz) || short.class.equals(clazz)) {
            return true;
        }
        if (Integer.class.equals(clazz) || int.class.equals(clazz)) {
            return true;
        }
        //赋值字段  小数
        if (Double.class.equals(clazz) || double.class.equals(clazz)) {
            return true;
        }
        if (Float.class.equals(clazz) || float.class.equals(clazz)) {
            return true;
        }
        //赋值字段  布尔
        if (Boolean.class.equals(clazz) || boolean.class.equals(clazz)) {
            return true;
        }
        if (Date.class.equals(clazz)) {
            return true;
        }
        if (LocalDateTime.class.equals(clazz)) {
            return true;
        }
        if (DataBusinessPage.class.equals(clazz)) {
            return true;
        }
        return false;
    }


    /**
     * 获取当前时间 - 根据时间格式
     * bao by 2017/3/29 21:26
     */
    public static String getTime(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date()).toString();
    }

    /**
     * 获取当前时间 - 根据时间格式
     * jch by 2017/3/29 21:26
     */
    public static String getNow() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date()).toString();
    }

    /**
     * 获取时间 - 根据指定时间和格式
     * bao by 2017/3/29 21:28
     */
    public static String getTime(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String time = sdf.format(date);
        return time;
    }

    /**
     * 获取时间 - 根据指定时间和格式
     * bao by 2017/3/29 21:28
     */
    public static String getTime(long second, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String time = sdf.format(second);
        return time;
    }


    /**
     * 对象转换Map
     * bao by 2017/3/29 22:00
     */
    public static Map<String, String> objectToMap(Object o) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            Class<?> c = Class.forName(o.getClass().getName());
            Method[] m = c.getMethods();
            String method = null;
            String key = null;
            Object value = null;

            for (int i = 0; i < m.length; i++) {
                method = m[i].getName();
                if (method.startsWith("get")) {
                    try {
                        value = m[i].invoke(o);
                        key = method.substring(3);
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                        if (value != null) {
                            map.put(key, String.valueOf(value));
                        } else {
                            map.put(key, null);
                        }
                    } catch (Exception ex) {
                        map.put(method, null);
                    }
                }
            }
        } catch (Exception ex) {
        }
        return map;
    }

    /**
     * 描述信息 获取IP地址
     * zy12 by 2018/2/4 16:31
     */
    public static String getIPAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ObjectUtil.isNull(ip) || ObjectUtil.equal(ip.length(), 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ObjectUtil.isNull(ip) || ObjectUtil.equal(ip.length(), 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ObjectUtil.isNull(ip) || ObjectUtil.equal(ip.length(), 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    /**
     * 检查Java类是否存在
     */
    public static boolean isValidJavaClass(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }


    // 获取文件后缀名
    public static String getSuffix(String filename) {
        int dotIndex = filename.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1);
        }
        return "";
    }

    // 去除文件名中的后缀
    public static String removeSuffix(String filename, String suffix) {
        if (suffix != null && !suffix.isEmpty()) {
            return filename.substring(0, filename.length() - suffix.length() - 1);
        }
        return filename;
    }

    /**
     * 检查文件夹是否存在
     */
    public static boolean folderExist(String path) {
        File file = new File(path);
        return file.exists();
    }


    /**
     * 判断系统是否为linux
     */
    public static boolean isLinux() {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().contains("linux")) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取文件id
     */
    public static List<Long> getArticleFileId(String content) {
        List<Long> list = new ArrayList<>();
        if (content == null) {
            return list;
        }

        try {
            Document doc = Jsoup.parse(content);
            Elements elementList = doc.getElementsByAttribute("src");
            for (Element element : elementList) {
                String src = element.attr("src");
                if (StrUtil.isEmpty(src)) {
                    continue;
                }
                URI uri = new URI(src);
                String queryParams = uri.getQuery();

                Map<String, String> map = getURLParams(queryParams);
                String fileId = map.get("fileId");
                if (fileId != null) {
                    list.add(Long.valueOf(fileId));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取url参数
     */
    public static Map<String, String> getURLParams(String queryParams) throws Exception {

        Map<String, String> parameters = new HashMap<>();

        if (queryParams != null && !queryParams.isEmpty()) {
            String[] pairs = queryParams.split("&");

            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    String key = keyValue[0];
                    String value = keyValue[1];
                    parameters.put(key, value);
                }
            }
        }

        return parameters;
    }

}